﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    static class ExpressionHelper
    {
        private readonly static ConcurrentDictionary<PropertyInfo, Func<object, object>> propertyGetterCache = new ConcurrentDictionary<PropertyInfo, Func<object, object>>();
        public static Func<object, object> GetValue(PropertyInfo propertyInfo)
        {
            return propertyGetterCache.GetOrAdd(propertyInfo, key =>
            {
                var instanceParam = Expression.Parameter(typeof(object), "instance");
                var castInstanceExpression = Expression.Convert(instanceParam, key.DeclaringType);
                var getter = key.GetGetMethod();
                var val = Expression.Call(castInstanceExpression, getter);
                var lambdaExpression = Expression.Lambda<Func<object, object>>(Expression.Convert(val, typeof(object)), instanceParam);
                return lambdaExpression.Compile();
            });
        }
    }
}
